package com.exam.common.exception;

import com.exam.common.api.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author wangwang
 * @date 2025/11/1 14:47
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public ApiResponse handle(ApiException e){
        log.error("捕获到 ApiException: {}", e.getMessage()); // 加日志
        if(e.getErrorCode() != null){
            return ApiResponse.failed(e.getErrorCode());
        }
        return ApiResponse.failed(e.getMessage());
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<?> handleException(Exception e) {
        log.error("系统异常", e);
        return ApiResponse.failed(e.getMessage());
    }
}
